﻿using System;
using System.Data;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Win32;

namespace Common
{
    /// <summary>
    /// Summary description for CmnProc.
    /// </summary>
    public static partial class CmnProc
    {
        /// <summary>
        /// 通过访问注册表，得到指定类型的 ContentType 。 IsMy_yxh
        /// </summary>
        /// <param name="strSuffix"></param>
        /// <returns></returns>
        public static string GetContentType(string strSuffix)
        {
            string strResult = string.Empty;
            try
            {
                RegistryKey key = Registry.LocalMachine;
                key = key.OpenSubKey("SOFTWARE\\Classes\\" + strSuffix);

                if (key != null)
                    strResult = key.GetValue("Content Type", "").ToString();
            }
            catch
            {
            }
            return strResult;
        }

        /// <summary>
        /// 如果没能取出Key ， 则返回 default()， 不会报错。  
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="R"></typeparam>
        /// <param name="TheDict"></param>
        /// <param name="One"></param>
        /// <returns></returns>
        public static R GetOrDefault<T, R>(this Dictionary<T, R> TheDict, T One)
        {
            if (TheDict == null) return default(R);
            if (TheDict.ContainsKey(One) == false)
                return default(R);
            return TheDict[One];
        }

        /// <summary>
        /// 依次遍历每个String ,获得其中不为空的 String 的值 , IsMy_yxh.
        /// </summary>
        /// <param name="SomeStrings"></param>
        /// <returns></returns>
        public static string GetValidOne(params string[] SomeStrings)
        {
            foreach (string item in SomeStrings)
            {
                if (item.HasValue() == true)
                    return item;
            }
            return string.Empty;
        }

        /// <summary>
        /// 替换 , " , 回车 -- \r \n &lt;  > \   IsMy_yxh
        /// </summary>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public static string GetSafeValue(this string Msg)
        {
            if (string.IsNullOrEmpty(Msg))
                return Msg;
            return Msg.Replace("'", "＇").Replace("\"", "＂").Replace(Environment.NewLine, " ").Replace("--", "－－").Replace("\r", "　").Replace("\n", " ").Replace("<", "＜").Replace(">", "＞").Replace("\\", "＼").Trim();
        }

        /// <summary>
        /// 将 NameValueCollection 转换成 字典 的形式 IsMy_yxh
        /// </summary>
        /// <param name="NameValueCollectionAsDataSource"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(this NameValueCollection NameValueCollectionAsDataSource)
        {
            Dictionary<string, string> retVal = new Dictionary<string, string>();
            foreach (string key in NameValueCollectionAsDataSource.AllKeys)
            {
                retVal.Add(key, NameValueCollectionAsDataSource[key]);
            }

            return retVal;
        }

        //public static T[] ToMyArray<T>(this IEnumerable<T> Value)
        //{
        //    if (Value == null) return null;

        //    List<T> list = new List<T>();

        //    IEnumerator<T> enr = Value.GetEnumerator();

        //    while (enr.MoveNext())
        //    {
        //        list.Add( enr.Current);
        //    }

        //    return list.ToArray();
        //}


        /// <summary>
        /// 得到 指定重复次数的 string 的表达式。 IsMy_yxh
        /// </summary>
        /// <param name="Value"></param>
        /// <param name="RepeatCount"></param>
        /// <returns></returns>
        public static string GetRepeatString(this string Value, int RepeatCount)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < RepeatCount; i++)
            {
                sb.Append(Value);
            }
            return sb.ToString();
        }


        ///// <summary>
        ///// 把 ICollection 转换为 List . 兼容模式. IsMy_yxh .
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="TheCollection"></param>
        ///// <returns></returns>
        //[Obsolete("这一个，要明确用法。")]
        //public static List<T> ToMyList<T>(this ICollection TheCollection) 
        //{
        //    List<T> retVal = new List<T>();
        //    var ienum = TheCollection.GetEnumerator();
        //    while (ienum.MoveNext())
        //    {
        //        retVal.Add( ValueProc.Get<T>(ienum.Current ) ) ;
        //    }
        //    return retVal;
        //}

        /// <summary>
        /// 检测 DataSet 是否包含有效数据。 IsMy_yxh
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool DataTableHasData(this DataTable data)
        {
            if (data == null)
                return false;
            if (data.Rows == null)
                return false;
            if (data.Rows.Count == 0)
                return false;
            return true;
        }

        /// <summary>
        /// 检测 DataSet 是否包含有效数据。 IsMy_yxh
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool DataSetHasData(this DataSet data)
        {
            if (data == null)
                return false;
            if (data.Tables == null)
                return false;
            if (data.Tables.Count == 0)
                return false;
            return data.Tables[0].DataTableHasData();
        }

        /// <summary>
        /// 比较两个 Array 的值 是否相等。 IsMy_yxh
        /// </summary>
        /// <param name="First"></param>
        /// <param name="Second"></param>
        /// <returns></returns>
        public static bool ArrayIsEqual(this Array First, Array Second)
        {
            if (First == null && Second == null)
                return true;
            if (First == null || Second == null)
                return false;
            if (First.Length != Second.Length)
                return false;

            for (int i = 0; i < First.Length; i++)
            {
                if (First.GetValue(i).Equals(Second.GetValue(i)) == false)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 浅拷贝可序列化的对象。 IsMy_yxh
        /// </summary>
        /// <typeparam name="T">浅拷贝的类型，该类型用扩展方法写的话。 可以不指定。</typeparam>
        /// <param name="obj">要浅拷贝的对象</param>
        /// <returns>浅拷贝后的对象。</returns>
        public static T SimpleCopySerializer<T>(this T obj)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, obj);

            object retval;
            ms.Seek(0, SeekOrigin.Begin);
            retval = bf.Deserialize(ms);
            ms.Close();
            return (T)retval;
        }

        public static string ResolveUrl(this string Url)
        {
            string strRoot = HttpContext.Current.Request.ApplicationPath.TrimEnd("/");
            //if (strRoot.HasValue() == false) strRoot = @"/"; 
            Url = Url.Trim();
            if (Url.StartsWith("~/"))
            {
                return strRoot + "/" + Url.TrimStart("~/");
            }
            /*
             else if (Url.StartsWith ("../")) {
                string[] urlArr = Url.Split (new string[] { "../" }, StringSplitOptions.None);
                int upLevel = urlArr.TakeWhile (o => o.Length == 0).Count ();
                string[] theArr = HttpContext.Current.Request.Url.ToString ().Split ('/');
                if (theArr.Length - upLevel > 2) {
                    return string.Join ("/", theArr.Take (theArr.Length - upLevel - 1).ToArray ()) + "/" + Url.TrimStart ("../");
                } else
                    return Url;
            } else if (Url.StartsWith ("./")) {
                string[] theArr = HttpContext.Current.Request.Url.ToString ().Split ('/');
                return string.Join ("/", theArr.Take (theArr.Length - 1).ToArray ()) + "/" + Url.TrimStart ("./");
            } */
            else
                return Url;
        }

        ///// <summary>
        ///// 得到  http://localhost  。 IsMy_yxh
        ///// </summary>
        ///// <returns></returns>
        //public static string GetUrlAuthority (this object ControlInMyPage)
        //{
        //    return HttpContext.Current.Request.Url.GetLeftPart (UriPartial.Authority);
        //}

        /// <summary>
        /// 得到  http://localhost/Path/  。 IsMy_yxh
        /// </summary>
        /// <returns></returns>
        public static string GetUrlHeader(this object ControlInMyPage)
        {
            return "~/".ResolveUrl();
        }

        /// <summary>
        /// 得到带有完整的路径。 
        /// 如:DocInfo/List.aspx?id=3 ，  http://localhost/jcysoft9.0/DocInfo/List.aspx?id=3   IsMy_yxh
        /// </summary>
        /// <param name="VirtualPath">从根目录开始的路径。</param>
        /// <returns></returns>
        public static string GetUrlFull(this string VirtualPath)
        {
            if (HttpContext.Current.CurrentHandler == null)
                return null;

            if (VirtualPath.StartsWith("http://") || VirtualPath.StartsWith("https://"))
                return VirtualPath;

            return VirtualPath.ResolveUrl();
        }
    }
}
